package com.kyxx.topics.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.kyxx.topics.BaseActivity;
import com.kyxx.topics.BaseApp;
import com.kyxx.topics.R;
import com.kyxx.topics.adapter.ImagePickerAdapter;
import com.kyxx.topics.net.LoadingStringCallBack;
import com.kyxx.topics.net.OkGoRequest;
import com.kyxx.topics.net.UrlUtils;
import com.kyxx.topics.utils.BitmapHelper;
import com.kyxx.topics.utils.StringUtil;
import com.kyxx.topics.utils.ToastUtils;
import com.kyxx.topics.widget.ClearEditText;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.request.BaseRequest;

import org.json.JSONException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class TipOffSubActivity extends BaseActivity implements ImagePickerAdapter.OnRecyclerViewItemClickListener, ImagePickerAdapter.DeleteImageView {


    @Bind(R.id.tv_tip_off_cancle)
    TextView tv_tip_off_cancle;
    @Bind(R.id.tv_tip_off_sub)
    TextView tv_tip_off_sub;
    @Bind(R.id.ed_tip_off_title)
    EditText ed_tip_off_title;
    @Bind(R.id.ed_tip_off_content)
    EditText ed_tip_off_content;
    @Bind(R.id.rv_tip_off_img)
    RecyclerView rv_tip_off_img;
    @Bind(R.id.et_tip_off_phone)
    ClearEditText et_tip_off_phone;
    @Bind(R.id.tv_tip_off_location)
    TextView tv_tip_off_location;
    @Bind(R.id.ll_reload)
    LinearLayout ll_reload;
    @Bind(R.id.rl_progress)
    RelativeLayout rl_progress;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;


    private ImagePickerAdapter adapter;
    private ArrayList<ImageItem> selImageList; //当前选择的所有图片
    private int maxImgCount = 9;               //允许选择图片最大数 p
    private Context ctx;
    private List<File> files;

    protected void findViewById() {
    }

    protected void loadViewLayout() {
        setContentView(R.layout.activity_tip_off_sub);
        ButterKnife.bind(this);
        ctx = this;
    }


    protected void processLogic() {
        rl_progress.setBackgroundColor(Color.argb(200,255,255,255));
        selImageList = new ArrayList<>();
        adapter = new ImagePickerAdapter(this, selImageList, maxImgCount);
        adapter.setOnItemClickListener(this);
        adapter.setDeleteImageView(this);
        rv_tip_off_img.setLayoutManager(new GridLayoutManager(this, 4));
        rv_tip_off_img.setHasFixedSize(true);
        rv_tip_off_img.setAdapter(adapter);
    }

    protected void setListener() {
    }

    @OnClick({R.id.tv_tip_off_cancle, R.id.tv_tip_off_sub,R.id.ll_reload})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tip_off_cancle:
                finish();
                break;
            case R.id.tv_tip_off_sub:
                if (StringUtil.isEmpty(ed_tip_off_title.getText().toString())) {
                    ToastUtils.show(context, "请填写标题");
                    return;
                }
                addBid();
                break;
            case R.id.ll_reload:
                if (StringUtil.isEmpty(ed_tip_off_title.getText().toString())) {
                    ToastUtils.show(context, "请填写标题");
                    return;
                }
                addBid();
                break;
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        switch (position) {
            case IMAGE_ITEM_ADD:
                //打开选择,本次允许选择的数量
                ImagePicker.getInstance().setSelectLimit(maxImgCount - selImageList.size());
                Intent intent = new Intent(this, ImageGridActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT);
                break;
            default:
                //打开预览
                Intent intentPreview = new Intent(this, ImagePreviewDelActivity.class);
                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                selImageList.addAll(images);
                adapter.setImages(selImageList);
            }
        } else if (resultCode == ImagePicker.RESULT_CODE_BACK) {
            //预览图片返回
            if (data != null && requestCode == REQUEST_CODE_PREVIEW) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_IMAGE_ITEMS);
                selImageList.clear();
                selImageList.addAll(images);
                adapter.setImages(selImageList);
            }
        }
    }

    @Override
    public void delete(int postion) {
        if (selImageList.size() > 0) {
            selImageList.remove(postion);
            adapter.setImages(selImageList);
        }
    }

    private void addBid() {
        final HttpParams params = new HttpParams();
        JSONObject obj = new JSONObject();
        obj.put("uid", BaseApp.getModel().getId());
        obj.put("title", ed_tip_off_title.getText().toString());
        obj.put("content", ed_tip_off_content.getText().toString());
        obj.put("mobile", et_tip_off_phone.getText().toString());
        //obj.put("address", tv_tip_off_location.getText().toString());
        obj.put("address", "");
        params.put("json", obj.toString());
        if (selImageList.size() > 0) {
            rl_progress.setVisibility(View.VISIBLE);
            for (int i = 0; i < selImageList.size(); i++) {
                ImageItem item = selImageList.get(i);
                Uri uri = Uri.parse(item.path);
                File file = BitmapHelper.ComressImgToFile((Activity) ctx, uri, 800, 1280);
                params.put("image" + (i + 1), file);
            }
        }
        OkGoRequest.post(UrlUtils.ADD_BID, context, "", CacheMode.NO_CACHE, params, new LoadingStringCallBack(TipOffSubActivity.this,true) {
            @Override
            public void parseError(Call call, Exception e) {
                super.parseError(call, e);
                ll_reload.setVisibility(View.VISIBLE);
            }

            @Override
            public void onBefore(BaseRequest request) {
                super.onBefore(request);
                if(rl_progress.getVisibility() != View.VISIBLE){
                    rl_progress.setVisibility(View.VISIBLE);
                }
                ll_reload.setVisibility(View.GONE);
            }

            @Override
            public void onAfter(@Nullable String s, @Nullable Exception e) {
                super.onAfter(s, e);
                if(rl_progress.getVisibility() != View.GONE){
                    rl_progress.setVisibility(View.GONE);
                }
                ll_reload.setVisibility(View.GONE);
            }

            @Override
            public void onCacheSuccess(String s, Call call) {
                super.onCacheSuccess(s, call);
                onSuccess(s, call, null);
            }

            @Override
            public void onSuccess(String s, Call call, Response response) {
                try {
                    org.json.JSONObject result = new org.json.JSONObject(s);
                    if (result.getInt("code") == 0) {
                        ToastUtils.show(context, "爆料成功");
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                ToastUtils.show(context, "网络错误请稍后再试");
            }
        });
    }


}